<template>
  <div class="DocumentApproval-container">
    <v-row class="main-wrap" no-gutters>
      <v-col class="list-wrap" :cols="4">
        <v-skeleton-loader
          v-if="listLoading"
          height="100%"
          tile
          type="list-item@20"
        ></v-skeleton-loader>
        <List
          v-else
          v-model="selectedDocument"
          :items="sortDocumentItems"
          title="Document Type"
        >
          <template #headerAppend>
            <v-row class="append-btn-group" no-gutters align="center">
              <v-col class="pr-4">
                <v-switch
                  v-model="isQuotation"
                  class="switch ma-0 pa-0"
                  color="#3B4765"
                  inset
                  dense
                  label="Quotation"
                ></v-switch>
              </v-col>
              <v-col>
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-icon
                      @click="openDeleteAmount"
                      v-on="on"
                      class="mr-2"
                      size="18"
                      color="#fff"
                    >
                      mdi-delete
                    </v-icon>
                  </template>
                  Delete Amount
                </v-tooltip>
              </v-col>
              <v-col>
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-icon
                      @click="openEditAmount"
                      v-on="on"
                      class="mr-2"
                      size="18"
                      color="#fff"
                    >
                      mdi-square-edit-outline
                    </v-icon>
                  </template>
                  Edit Amount
                </v-tooltip>
              </v-col>
              <v-col>
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-icon
                      @click="openAddAmount"
                      v-on="on"
                      color="#fff"
                      class="icon"
                    >
                      mdi-plus
                    </v-icon>
                  </template>
                  Add Amount
                </v-tooltip>
              </v-col>
            </v-row>
          </template>
          <template #itemAppend="{ item }">
            <v-text-field
              v-model="item.amount"
              disabled
              solo
              flat
              hide-details
              class="input"
            ></v-text-field>
          </template>
          <template #label="{ item }">
            {{ item.documentType }}
          </template>
        </List>
      </v-col>
      <v-col class="table-wrap">
        <v-skeleton-loader
          v-if="documentApprovalLoading"
          height="100%"
          tile
          type="list-item@20"
        ></v-skeleton-loader>
        <Table
          v-else-if="documentApprovalItems.length"
          :title="documentApprovalTitle"
          :headers="documentApprovalHeaders"
          :items="documentApprovalItems"
          disable-sort
          hide-default-footer
        >
          <template #[`header.action`]>
            <v-icon
              @click="saveDocumentApproval"
              color="#fff"
              size="18"
              class="mr-2 pointer"
            >
              mdi-content-save
            </v-icon>
          </template>
          <template #item="{ item }">
            <tr class="table-content">
              <td class="text-start">{{ item.userId }}</td>
              <td class="text-center">
                <v-select
                  v-model="item.stage"
                  :items="[1, 2, 3]"
                  flat
                  solo
                  hide-details
                  class="gray-input input-select"
                ></v-select>
              </td>
              <td
                class="text-center"
                v-for="header in documentApprovalHeaders.slice(
                  2,
                  documentApprovalHeaders.length - 1
                )"
                :key="header.value"
              >
                <input
                  v-model="item.approval"
                  :value="header.value"
                  :name="item.id"
                  class="radio pointer"
                  type="radio"
                />
              </td>
              <td class="action-icon-group text-right">
                <div class="action">
                  <v-icon
                    @click="openSelectApprovalUser"
                    class="mr-2 pointer"
                    color="#79839B"
                    size="20"
                  >
                    mdi-plus-thick
                  </v-icon>
                  <v-icon
                    @click="deleteApprovalUser(item)"
                    class="pointer"
                    color="#79839B"
                    size="20"
                  >
                    mdi-delete
                  </v-icon>
                </div>
              </td>
            </tr>
          </template>
        </Table>
      </v-col>
    </v-row>
    <Dialog
      v-model="showDialog"
      @submit="saveAmount"
      :title="dialogTitle"
      :show-save="step !== 3"
      width="480"
    >
      <template>
        <AddEditAmount
          v-if="[1, 2].includes(step)"
          ref="addEditAmount"
        ></AddEditAmount>
        <DeleteAmount
          v-else-if="step === 3 && selectedDocument"
          @delete="deleteAmount"
          :item="selectedDocument"
        ></DeleteAmount>
      </template>
    </Dialog>
    <Select
      :show.sync="showSelectApprovalUserDialog"
      :show-save="false"
      :headers="selectApprovalUserHeader"
      :items="selectApprovalUsers"
      @select="addApprovalUser"
      title="Select User ID"
      width="904"
    ></Select>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import List from "@/components/Maintenance/List/List.vue";
import Table from "@/components/Maintenance/Table/Table.vue";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import Select from "@/components/Quotation/Dialog/Select/Select.vue";
import AddEditAmount from "@/components/Maintenance/Admin/DocumentApproval/AddEditAmount.vue";
import DeleteAmount from "@/components/Maintenance/Admin/DocumentApproval/DeleteAmount.vue";
interface IDocumentItem {
  id: string;
  documentType: string;
  amount: string;
}
interface IApprovalUser {
  id: string;
  userId: string;
  name: string;
  code: string;
}
interface IDocumentApproval {
  id: string;
  userId: string;
  stage: number;
  approval: string;
}
@Component({
  components: {
    List,
    Table,
    Dialog,
    Select,
    AddEditAmount,
    DeleteAmount,
  },
})
export default class DocumentApproval extends Vue {
  isQuotation = false;
  @Watch("isQuotation")
  onSortDocumentItemsChange() {
    this.setDefaultDocument();
  }
  // 1.addAmount 2.editAmount 3.deleteAmount
  step = -1;
  // dialog
  showDialog = false;
  dialogTitle = "";
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }

  // document list
  listLoading = false;
  documentItems: IDocumentItem[] = [];
  get sortDocumentItems() {
    return this.documentItems.filter((item) => {
      return (
        item.documentType ===
        (this.isQuotation ? "QUOT- Quotation" : "INV- Invoice")
      );
    });
  }
  selectedDocument: IDocumentItem | null = null;
  @Watch("selectedDocument")
  onSelectedDocumentChange(IDocumentItem: IDocumentItem | undefined) {
    if (IDocumentItem) {
      this.getDocumentApprovalItems();
    } else {
      this.documentApprovalItems = [];
    }
  }
  getDocumentItems() {
    this.listLoading = true;
    setTimeout(() => {
      this.documentItems = [
        {
          id: "0",
          documentType: "INV- Invoice",
          amount: "12,000.00",
        },
        {
          id: "1",
          documentType: "QUOT- Quotation",
          amount: "78,000.00",
        },
      ];
      this.listLoading = false;
      this.setDefaultDocument();
    }, 800);
  }
  setDefaultDocument() {
    if (this.sortDocumentItems.length) {
      this.selectedDocument = this.sortDocumentItems[0];
    }
  }
  openAddAmount() {
    this.step = 1;
    this.dialogTitle = "Add Amount";
    this.$nextTick(() => {
      const addEditAmountRef = this.$refs.addEditAmount as AddEditAmount;
      addEditAmountRef.resetForm();
    });
    this.openDialog();
  }
  openEditAmount() {
    if (this.selectedDocument) {
      this.step = 2;
      this.dialogTitle = "Edit Amount";
      this.$nextTick(() => {
        const addEditAmountRef = this.$refs.addEditAmount as AddEditAmount;
        addEditAmountRef.resetForm();
        setTimeout(() => {
          addEditAmountRef.setFormData(this.selectedDocument as IDocumentItem);
        });
      });
      this.openDialog();
    } else {
      this.SweetAlertService.warning(
        "Please select the amount you want to edit"
      );
    }
  }
  openDeleteAmount() {
    if (this.selectedDocument) {
      this.step = 3;
      this.dialogTitle = "Delete Amount";
      this.openDialog();
    } else {
      this.SweetAlertService.warning(
        "Please select the amount you want to delete"
      );
    }
  }
  async saveAmount() {
    const addEditAmountRef = this.$refs.addEditAmount as AddEditAmount;
    const result = await addEditAmountRef.validateFormData();
    if (result) {
      if (this.step === 1) {
        result.id = String(new Date().getTime());
        result.documentType = this.isQuotation
          ? "QUOT- Quotation"
          : "INV- Invoice";
        this.addAmount(result as IDocumentItem);
      } else if (this.step === 2) {
        this.editAmount(result as IDocumentItem);
      }
      this.closeDialog();
    }
  }
  addAmount(item: IDocumentItem) {
    this.documentItems.push(item);
  }
  editAmount(documentItem: IDocumentItem) {
    const oldDocumentItem = this.documentItems.find(
      (item) => item.id === documentItem.id
    );
    Object.assign(oldDocumentItem as IDocumentItem, documentItem);
  }
  deleteAmount(documentItem: IDocumentItem) {
    const index = this.documentItems.findIndex(
      (item) => item.id === documentItem.id
    );
    this.documentItems.splice(index, 1);
    this.closeDialog();
  }
  // Document Approval
  documentApprovalLoading = false;
  get documentApprovalTitle() {
    if (this.selectedDocument) {
      return `${this.selectedDocument.documentType.split("-")[0]} >=${
        this.selectedDocument.amount
      }`;
    }
    return "";
  }

  documentApprovalHeaders = [
    {
      text: "User ID",
      value: "userId",
    },
    {
      text: "Stage",
      value: "stage",
      align: "center",
      width: "114",
    },
    {
      text: "Required",
      value: "required",
      align: "center",
    },
    {
      text: "Anyone",
      value: "anyone",
      align: "center",
    },
    {
      text: "Not required",
      value: "notRequired",
      align: "center",
    },
    {
      text: "N/A",
      value: "notApplicable",
      align: "center",
    },
    {
      value: "action",
      align: "end",
    },
  ];

  documentApprovalItems: IDocumentApproval[] = [];
  getDocumentApprovalItems() {
    this.documentApprovalLoading = true;
    setTimeout(() => {
      this.documentApprovalItems = [
        {
          id: "1",
          userId: "ADM2",
          stage: 2,
          approval: "required",
        },
        {
          id: "2",
          userId: "User2",
          stage: 1,
          approval: "notApplicable",
        },
      ];
      this.documentApprovalLoading = false;
    }, 1000);
  }
  saveDocumentApproval() {
    this.SweetAlertService.success("Save successfully");
  }
  addApprovalUser(item: IApprovalUser) {
    console.log(item, this.documentApprovalItems);
    const approvalUserExist = this.documentApprovalItems.findIndex(
      (approvalUser) => approvalUser.userId === item.userId
    );
    if (approvalUserExist !== -1) {
      this.SweetAlertService.warning("The User already exists");
      return;
    }
    const documentApprovalItem = {
      id: String(new Date().getTime()),
      userId: item.userId,
      stage: 1,
      approval: "required",
    };
    this.documentApprovalItems.push(documentApprovalItem);
    this.closeSelectApprovalUser();
  }
  deleteApprovalUser(item: IDocumentApproval) {
    const index = this.documentApprovalItems.indexOf(item);
    this.documentApprovalItems.splice(index, 1);
  }
  // Select Approval User
  selectApprovalUserLoading = false;
  showSelectApprovalUserDialog = false;
  selectApprovalUserHeader = [
    {
      text: "Usre ID",
      value: "userId",
    },
    {
      text: "User Name",
      value: "name",
    },
    {
      text: "Department Code",
      value: "code",
    },
  ];
  selectApprovalUsers: IApprovalUser[] = [];

  getSelectApprovalUserItems() {
    this.selectApprovalUserLoading = true;
    setTimeout(() => {
      this.selectApprovalUsers = [
        {
          id: "1",
          userId: "Team1",
          name: "Team1",
          code: "ADM",
        },
        {
          id: "2",
          userId: "Admin",
          name: "System Administractor",
          code: "ADM",
        },
      ];
      this.selectApprovalUserLoading = false;
    }, 1500);
  }
  openSelectApprovalUser() {
    this.showSelectApprovalUserDialog = true;
  }
  closeSelectApprovalUser() {
    this.showSelectApprovalUserDialog = false;
  }
  // action
  created() {
    this.getDocumentItems();
    this.getSelectApprovalUserItems();
  }
  mounted() {
    this.$store.commit("MaintenanceStore/closeActionIcon");
  }
}
</script>

<style lang="scss" scoped>
@import "./DocumentApproval.scss";
</style>
